
import { reqCartList } from "@/api";
import { reqDeleteCartById, reqUpdateCheckedByid } from "@/api";

const state = {
    cartList: []
};
const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList
    }
};
const actions = {
    async getCartList({ commit }) {

        let result = await reqCartList()
        console.log(result)
        if (result.code == 200) {
            commit("GETCARTLIST", result.data)
        }
    },
    async deleteCartListBySkuId({ commit }, skuId) {

        let result = await reqDeleteCartById(skuId)
        console.log(result)
        if (result.code == 200) {
            return "ok"
        } else {
            return Promise.reject(new Error("failed"))
        }
    },

    deleteAllCheckedCart({ dispatch, getters }) {
        
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach((item) => {
            let promise = item.isChecked == 1 ? dispatch("deleteCartListBySkuId", item.skuId) : ""
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)
    },

    async updateCheckedById({ commit }, { skuId, isChecked }) {
        
        let result = await reqUpdateCheckedByid(skuId, isChecked)
        console.log(result)
        if (result.code == 200) {
            return "ok"
        } else {
            return Promise.reject(new Error("failed"))
        }
    },
    updateAllCartIsChecked({ dispatch, state }, isChecked) {
        
        let promiseAll = []
        state.cartList[0].cartInfoList.forEach((item) => {
            
            let promise = dispatch("updateCheckedById", {
                skuId: item.skuId,
                isChecked
            })
            promiseAll.push(promise)
        })
        return Promise.all(promiseAll)
    }
};
const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    }
};
export default {
    state,
    mutations,
    actions,
    getters
}